package com.zzh.htts.voice


import android.speech.tts.TextToSpeech.QUEUE_ADD
import android.text.TextUtils
import com.zzh.lib.htts.HTTSLib
import com.zzh.lib.htts.callback.OnUtteranceProgressListener
import java.util.concurrent.ConcurrentLinkedQueue

/**
 * Created by zzh on 2025/5/19.
 * @date: 2025/5/19 14:24
 * @email: zzh_hz@126.com
 * @author: zzh
 * @description: com.zzh.htts.voice
 */

// 事件监听接口
interface TtsQueueListener {
    fun onEnd()
}

// 单例任务队列
object TtsTaskQueue {

    // 线程安全队列
    private val stringQueue = ConcurrentLinkedQueue<String>()

    // 监听器集合
    private val listeners = mutableSetOf<TtsQueueListener>()
    private val lock = Any()
    private var isActive = false

    private val handleCallback = object : OnUtteranceProgressListener() {

        override fun onDone(utteranceId: String?) {
            super.onDone(utteranceId)
            startProcessing()
        }

    }


    /**
     * 添加字符串到队列（支持多线程调用）
     */
    fun addString(text: String) {
        if (TextUtils.isEmpty(text)) {
            return
        }

        synchronized(lock) {
            stringQueue.add(text)
            if (!isActive) {
                isActive = true
                startProcessing()
            }
        }
    }

    /**
     * 清空所有队列内容
     */
    fun clearAll() {
        synchronized(lock) {
            stringQueue.clear()
        }
    }

    /**
     * 注册监听器
     */
    fun registerListener(listener: TtsQueueListener) {
        synchronized(lock) {
            listeners.add(listener)
        }
    }

    /**
     * 注销监听器
     */
    fun unregisterListener(listener: TtsQueueListener) {
        synchronized(lock) {
            listeners.remove(listener)
        }
    }


    // 启动处理循环
    private fun startProcessing() {
        val poll = stringQueue.poll()
        if (poll != null && !TextUtils.isEmpty(poll)) {
            if (TextUtils.equals("end", poll)) {
                isActive = false
                for (listener in listeners) {
                    listener.onEnd()
                }
            } else {
                HTTSLib.getInstance().speak(poll, QUEUE_ADD, handleCallback)
            }
        } else {
            isActive = false
        }

    }

    /**
     * 关闭队列（释放资源）
     */
    fun shutdown() {
        clearAll()
    }
}
